﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SanPham_ShoppingCart : System.Web.UI.Page
{
    static DataTable tbPro = new DataTable();
    private int id1 = 0;
    private float sum = 0;

    public int Id1
    {
        get { return id1; }
        set { id1 = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {


        if (Session["Username"] != null)
        {
            btnRedirect.Visible = true;
            BtnLogin.Visible = false;
            BtnLogout.Visible = true;
            BtnOrder.Visible = true;
        }
        else
        {
            BtnOrder.Visible = false;
            btnRedirect.Visible = false;
            BtnLogin.Visible = true;
            BtnLogout.Visible = false;
        }


        if (!IsPostBack)
        {
            load_data();
        }
        loadOID();
        loadSum();
        
    }

    private void loadOID()
    {
        String strCon = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ToString();
        SqlConnection myCon = new SqlConnection(strCon);
        myCon.Open();
        string sql1 = "select top 1 OID from _Order ORDER BY OID Desc";
        SqlCommand cmd1 = new SqlCommand(sql1,myCon);
        SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
        DataTable dt1 = new DataTable();
        da1.Fill(dt1);
        try
        {
            Id1 = int.Parse(dt1.Rows[0][0].ToString());
        }
        catch (Exception)
        {
            Id1 = 0;
        }
        myCon.Close();
        Session["OID"] = Id1 + 1;
    }

    private void loadSum() 
    {
        DataTable shopCart = (DataTable)Session["ShoppingCart"];
        for (int i = 0; i < shopCart.Rows.Count; i++)
        {
            
            sum += (float.Parse(shopCart.Rows[i][2].ToString()) * float.Parse(shopCart.Rows[i][3].ToString()));
        }
        lblSum.Text = sum.ToString();
        Session["Sum"] = sum;
    }

    private void load_data()
    {
        if (Request.QueryString["PID"] != null)
        {
            String strCon = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ToString();
            SqlConnection myCon = new SqlConnection(strCon);
            myCon.Open();
            string id = Request.QueryString["PID"];
            string sql = "Select Name,Price From _Product where PID = '{0}'";
            sql = string.Format(sql,id);
            SqlCommand cmd = new SqlCommand(sql, myCon);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);        
           
            string name = dt.Rows[0][0].ToString();
            string price = dt.Rows[0][1].ToString();
            int quantity = 1;
            AddToCart(id, name, price, quantity);
            
        }
        if (Session["ShoppingCart"] == null)
        {
            Response.Redirect("../Product/Product.aspx");
        }
        tbPro = (DataTable)Session["ShoppingCart"];
        //string sum = tbPro.Compute("Sum(Sum)", "").ToString();
        //lblSum.Text = sum;
        gvCart.DataSource = tbPro;
        gvCart.DataBind();
    }
    public void AddToCart(string id, string name, string price, int quantity)
    {
        DataTable dt;
        if (Session["ShoppingCart"] == null)
        {
            dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");
            dt.Columns.Add("Price");
            dt.Columns.Add("Quantity");
            //dt.Columns.Add("Sum");
        }
        else
        {
            dt = (DataTable)Session["ShoppingCart"];
        }
        int dong = existed(id, dt);
        if (dong != -1)
        {
            dt.Rows[dong]["Quantity"] = Convert.ToInt32(dt.Rows[dong]["Quantity"]) + quantity;
        }
        else
        {
            DataRow dr = dt.NewRow();
            dr["Id"] = id;
            dr["Name"] = name;
            dr["Price"] = price;
            dr["Quantity"] = quantity;
            //dr["Sum"] = sum;
            dt.Rows.Add(dr);
        }
        Session["ShoppingCart"] = dt;
    }
    public static int existed(string id, DataTable dt)
    {
        int dong = -1;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["Id"].ToString() == id)
            {
                dong = i;
                break;
            }
        }
        return dong;
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Product/Product.aspx");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable shopCart = (DataTable)Session["ShoppingCart"];
        String strCon = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ToString();
        SqlConnection myCon = new SqlConnection(strCon);
        myCon.Open();
        
        for (int j = 0; j < shopCart.Rows.Count; j++) 
        {
            string sql1 = "select Stocked from _Product where PID = '{0}'";
            sql1 = string.Format(sql1,shopCart.Rows[j][0].ToString());
            SqlCommand cmd1 = new SqlCommand(sql1, myCon);
            SqlDataAdapter da = new SqlDataAdapter(cmd1);
            DataTable dt = new DataTable();
            da.Fill(dt);

            if (int.Parse(shopCart.Rows[j][3].ToString()) > int.Parse(dt.Rows[0][0].ToString())) 
            {
                Label1.Text = string.Format("{0} is out of stocked",shopCart.Rows[j][1].ToString());
                return;
            }
            string sql = "insert into _Order (OID,PID,Quantity) values ({0},'{1}',{2}) ";
            sql = string.Format(sql, (Id1 + 1), shopCart.Rows[j][0].ToString(),shopCart.Rows[j][3].ToString());
            SqlCommand cmd = new SqlCommand(sql, myCon);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
            }
            string sql2 = "update _Product set Stocked = '{0}' where PID = '{1}'";
            sql2 = string.Format(sql2, "" + (int.Parse(dt.Rows[0][0].ToString()) - int.Parse(shopCart.Rows[j][3].ToString())), shopCart.Rows[j][0].ToString());
            SqlCommand cmd2 = new SqlCommand(sql2, myCon);
            try
            {
                cmd2.ExecuteNonQuery();
            }
            catch (Exception)
            {
            }
        }
        myCon.Close();
        Response.Redirect("../Customer/Customer.aspx");
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        Session["ShoppingCart"] = null;
        Response.Redirect("../Product/Product.aspx");
    }
    protected void btnRedirect_Click(object sender, EventArgs e)
    {
        clsLogIn a = (clsLogIn)(Session["Username"]);

        if (a.IsAdmin)
        {
            Response.Redirect("../User Information/Information.aspx");
        }
        else
        {
            Response.Redirect("../Add Products/AddProducts.aspx");
        }
    }
    protected void BtnLogin_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Login/Login.aspx");

    }
    protected void BtnLogout_Click1(object sender, EventArgs e)
    {
        Session["Username"] = null;
        Response.Redirect("../Login/Login.aspx");
    }
    protected void BtnOrder_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Order/Default.aspx");
    }
}